<template>
  <div class="paid-bill-management">
    <div style="margin-bottom: 15px;">
      <h3>已缴账单</h3>
    </div>
    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="card" class="tabs">
      <el-tab-pane label="缴费记录" name="record">
        <!-- 操作栏：按钮 + 搜索 -->
        <div class="operation-bar">
          <el-button type="primary" @click="importBills">导入已缴账单</el-button>
          <el-button @click="deleteBills">删除</el-button>
          <div class="search-group" style="margin-left: auto;">
            <el-input v-model="searchKeyword" placeholder="小区/房号/收费项目/收费标准" style="width: 240px;" />
            <el-button type="primary" icon="el-icon-search" @click="searchBills"></el-button>
            <el-button type="primary" icon="el-icon-filter" @click="filterBills"></el-button>
          </div>
        </div>

        <!-- 已缴账单表格 -->
        <el-table :data="tableData" border style="width: 100%; margin-bottom: 20px;"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="communityName" label="小区" />
          <el-table-column prop="number" label="房号/车位号/车牌号/住户" width="180" />
          <el-table-column prop="clientName" label="住户姓名" />
          <el-table-column prop="clientPhone" label="手机号" width="150" />
          <el-table-column prop="pricingName" label="费用名称" width="180" />
          <el-table-column prop="settingPrice" label="单价" />
          <el-table-column prop="billNumber" label="数量" />
          <el-table-column prop="billSum" label="应收金额" />
          <el-table-column prop="settingPrice" label="实收金额" />
          <el-table-column label="操作" width="220">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="viewBill(scope.row)">查看</el-button>
              <el-button type="danger" size="small" plain @click="refundBill(scope.row)">退款</el-button>
              <el-button type="danger" size="small" plain @click="deleteBill(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrap">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
            layout="prev, pager, next, ->, jumper, ->, sizes, total" :total="total" />
        </div>
      </el-tab-pane>
      <el-tab-pane label="缴费明细" name="detail" />
      <el-tab-pane label="回收站" name="recycle" />
    </el-tabs>
  </div>
</template>

<script>
import { billApi } from '@/api/bill'
import request from '@/utils/request';

export default {
  name: 'PaidBillManagement',
  data() {
    return {
      activeTab: 'record',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      selectedRows: [],
      searchKeyword: '',
      selectedReceivable: 0,
      selectedDiscount: 0,
      selectedOverdueFine: 0,
      selectedActualAmount: 0
    }
  },
  created() {
    this.fetchBills();
  },
  methods: {
    async fetchBills() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          billStatus: 1
        };

        const response = await billApi.getBillByStatus(params);
        if (response.code === 200) {
          console.log('获取账单数据成功:', response);
          this.tableData = response.data.records;
          this.total = response.data.total;
        } else {
          console.error('获取账单数据失败:', response.message);
          this.$message.error(response.message || '获取账单数据失败');
        }
      } catch (error) {
        console.error('请求账单数据时发生错误:', error);
        this.$message.error('获取账单数据失败');
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchBills();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchBills();
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      this.selectedReceivable = this.selectedRows.reduce((sum, row) => sum + row.billSum, 0);
      this.selectedDiscount = this.selectedRows.reduce((sum, row) => sum + row.discount, 0);
      this.selectedOverdueFine = this.selectedRows.reduce((sum, row) => sum + row.overdueFine, 0);
      this.selectedActualAmount = this.selectedRows.reduce((sum, row) => sum + row.actualAmount, 0);
    },
    importBills() {
      // 导入账单逻辑
    },
    deleteBills() {
      // 删除账单逻辑
    },
    searchBills() {
      // 搜索账单逻辑
    },
    filterBills() {
      // 过滤账单逻辑
    },
    viewBill(row) {
      this.$router.push({
        path: '/bill/detail',
        query: { billId: row.billId }
      });
    },
    refundBill(row) {
      this.$prompt('请输入退款原因', '退款确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{5,100}$/,
        inputErrorMessage: '退款原因需5-100个字符'
      }).then(async ({ value }) => {
        try {
          const response = await billApi.refundBill({
            billId: row.billId,
            reason: value
          });
          if (response.code === 200) {
            this.$message.success('退款申请已提交');
            this.fetchBills();
          } else {
            this.$message.error(response.message || '退款失败');
          }
        } catch (error) {
          console.error('退款失败:', error);
          this.$message.error('退款失败');
        }
      }).catch(() => { });
    },
    deleteBill(row) {
      const billId = row.billId;  // 获取要删除的账单id
      this.$confirm('确定要删除该账单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用删除接口
          const response = await billApi.deleteBillById(billId);
          console.log('删除成功:', response);
          this.$message.success('删除成功');
          this.fetchBills();  // 重新加载数据
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>
.paid-bill-management {
  padding: 20px;
}

.function-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
}

.tabs {
  margin-bottom: 15px;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-group .el-input {
  margin-right: 8px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
}
</style>
